#include "adc.h"

uint16_t read_adc(uint8_t mux)
{
	uint16_t val;			// the value
	
	// setting up the ADC with frequency 4
	ADCSRA = (1<<ADEN) | (1<<ADPS1) | (1<<ADPS0);
	ADMUX = mux;			// select the channel
	ADMUX |= (1<<REFS0) | (1<<REFS1);	// select the referencevoltage
	
	ADCSRA |= (1<<ADSC);	// dummy-read
	
	val = 0;
	for(int i = 0; i < 4; ++i) {
		while(ADCSRA & (1<<ADSC)) {	// here we go...
			// wait for finish
		}
		val += ADCW;
	}
	// calculate the average of 4 measures
	val /= 4;
	// deactivate the ADC
	ADCSRA &= ~(1<<ADEN);
	return val;
}

